package org.Yiran.timetale_re.client.gui;

import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Axis;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.Yiran.timetale_re.item.runeblueprint.base.RuneBlueprintItem;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * 符文蓝图手册查看模型屏幕
 * 用于在GUI中查看符文蓝图手册中存储的图纸3D模型
 * 支持翻页浏览多张图纸，每张图纸以3D模型形式展示
 */
@OnlyIn(Dist.CLIENT)
public class RuneBlueprintBookViewModelScreen extends Screen {
    
    // ==================== 常量定义 ====================
    
    /** GUI宽度 */
    private static final int GUI_WIDTH = 256;
    
    /** GUI高度 */
    private static final int GUI_HEIGHT = 166;

    // ==================== 实例变量 ====================

    /** 手册物品堆 */
    private final ItemStack bookStack;
    
    /** 存储的蓝图列表 */
    private final List<ItemStack> blueprints = new ArrayList<>();
    
    /** 当前页面索引 */
    private int currentPage = 0;
    
    /** 下一页按钮 */
    private Button nextButton;
    
    /** 上一页按钮 */
    private Button prevButton;
    
    /** GUI顶部Y坐标 */
    private int guiTop;

    // ==================== 构造函数 ====================

    /**
     * 构造函数
     * @param bookStack 手册物品堆
     */
    public RuneBlueprintBookViewModelScreen(ItemStack bookStack) {
        super(Component.translatable("screen.timetale_re.rune_blueprint_book_view"));
        this.bookStack = bookStack;
        
        // 从NBT加载图纸
        loadBlueprintsFromNBT();
    }
    
    /**
     * 从NBT数据加载蓝图
     */
    private void loadBlueprintsFromNBT() {
        if (bookStack.getTag() != null && bookStack.hasTag() && bookStack.getTag().contains("BookInventory")) {
            CompoundTag bookInventoryTag = bookStack.getTag().getCompound("BookInventory");
            if (bookInventoryTag.contains("Items")) {
                ListTag itemsList = bookInventoryTag.getList("Items", 10);
                
                for (int i = 0; i < itemsList.size(); i++) {
                    CompoundTag itemTag = itemsList.getCompound(i);
                    ItemStack slotItem = ItemStack.of(itemTag);
                    
                    if (slotItem.getItem() instanceof RuneBlueprintItem) {
                        blueprints.add(slotItem);
                    }
                }
            }
        }
    }

    // ==================== 初始化方法 ====================

    @Override
    protected void init() {
        int guiLeft = (this.width - GUI_WIDTH) / 2;
        this.guiTop = (this.height - GUI_HEIGHT) / 2;

        // 根据图纸数量决定是否显示翻页按钮
        if (!blueprints.isEmpty()) {
            // 添加翻页按钮
            int buttonWidth = 20;
            int buttonHeight = 20;

            this.nextButton = this.addRenderableWidget(Button.builder(Component.literal(">"), (btn) -> {
                        nextPage();
                        updateButtonStates();
                    })
                    .pos(guiLeft + GUI_WIDTH - buttonWidth + 5, guiTop + GUI_HEIGHT / 2)
                    .size(buttonWidth, buttonHeight)
                    .build());

            this.prevButton = this.addRenderableWidget(Button.builder(Component.literal("<"), (btn) -> {
                        prevPage();
                        updateButtonStates();
                    })
                    .pos(guiLeft - 5, guiTop + GUI_HEIGHT / 2)
                    .size(buttonWidth, buttonHeight)
                    .build());

            updateButtonStates();
        }
    }

    // ==================== 页面导航方法 ====================

    /**
     * 切换到下一页
     */
    private void nextPage() {
        if (nextButton != null && currentPage < blueprints.size() - 1) {
            currentPage++;
            updateButtonStates();
            playPageTurnSound();
        }
    }

    /**
     * 切换到上一页
     */
    private void prevPage() {
        if (prevButton != null && currentPage > 0) {
            currentPage--;
            updateButtonStates();
            playPageTurnSound();
        }
    }

    /**
     * 更新按钮状态
     */
    private void updateButtonStates() {
        if (nextButton != null) {
            nextButton.active = currentPage < blueprints.size() - 1;
        }
        if (prevButton != null) {
            prevButton.active = currentPage > 0;
        }
    }

    // ==================== 音效方法 ====================

    /**
     * 播放翻页音效
     */
    private void playPageTurnSound() {
        Minecraft mc = Minecraft.getInstance();
        if (mc.level != null) {
            if (mc.player != null) {
                mc.level.playLocalSound(
                        mc.player.getX(),
                        mc.player.getY(),
                        mc.player.getZ(),
                        SoundEvents.BOOK_PAGE_TURN,
                        SoundSource.PLAYERS,
                        1.0F,
                        1.0F,
                        false
                );
            }
        }
    }

    // ==================== 渲染方法 ====================

    @Override
    public void render(@NotNull GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) {
        this.renderBackground(guiGraphics);
        super.render(guiGraphics, mouseX, mouseY, partialTicks);

        // 添加鼠标悬停检测 - 只有在按钮存在时才执行
        if (nextButton != null) {
            nextButton.setFocused(nextButton.isHovered());
        }
        if (prevButton != null) {
            prevButton.setFocused(prevButton.isHovered());
        }

        // 绘制当前页面的图纸模型
        if (!blueprints.isEmpty() && currentPage < blueprints.size()) {
            ItemStack blueprint = blueprints.get(currentPage);
            renderBlueprintModel(guiGraphics, blueprint);

            // 显示图纸名称和页码
            String runeType = RuneBlueprintItem.getRuneType(blueprint);
            if (runeType != null && !runeType.isEmpty()) {
                String translationKey = "item.timetale_re." + runeType + "_rune_blueprint";
                String displayName = Component.translatable(translationKey).getString();
                guiGraphics.drawCenteredString(font, displayName, width / 2, guiTop + GUI_HEIGHT, 0xFFFFFF);
            }

            guiGraphics.drawCenteredString(font, (currentPage + 1) + "/" + blueprints.size(), width / 2, guiTop + GUI_HEIGHT + 15, 0xAAAAAA);
        } else {
            // 显示空图册提示
            guiGraphics.drawCenteredString(font, Component.translatable("gui.timetale_re.rune_blueprint_book.empty").getString(),
                    width / 2, height / 2 - 25, 0xAAAAAA);
        }
    }

    /**
     * 渲染蓝图模型
     * @param guiGraphics GUI图形绘制对象
     * @param blueprint 蓝图物品堆
     */
    private void renderBlueprintModel(GuiGraphics guiGraphics, ItemStack blueprint) {
        // 获取符文类型
        String runeType = RuneBlueprintItem.getRuneType(blueprint);
        if (runeType == null || runeType.isEmpty()) {
            return;
        }

        PoseStack poseStack = guiGraphics.pose();
        poseStack.pushPose();

        // 定位到屏幕中心
        poseStack.translate(width / 2.0f, height / 2.0f - 10, 100.0f);

        // 应用缩放
        float scaleFactor = 1.0f;
        poseStack.scale(scaleFactor * 50, -scaleFactor * 50, scaleFactor * 50);

        poseStack.mulPose(Axis.XP.rotationDegrees(1));
        poseStack.mulPose(Axis.ZP.rotationDegrees(180));

        // 获取模型资源位置
        ResourceLocation modelLocation = ResourceLocation.fromNamespaceAndPath("timetale_re", "block/rune_blueprint/rune_blueprint_" + runeType);

        // 获取烘焙模型
        BakedModel model = Minecraft.getInstance().getModelManager().getModel(modelLocation);

        // 渲染模型
        MultiBufferSource.BufferSource bufferSource = Minecraft.getInstance().renderBuffers().bufferSource();
        Minecraft.getInstance().getItemRenderer().render(
                blueprint,
                ItemDisplayContext.GUI,
                false,
                poseStack,
                bufferSource,
                0xFFFFFF, // 使用白色作为基础颜色
                OverlayTexture.NO_OVERLAY,
                model
        );
        bufferSource.endBatch();

        poseStack.popPose();
    }
    
    // ==================== 其他方法 ====================

    @Override
    public boolean isPauseScreen() {
        return false;
    }
}